package com.sq.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sq.common.to.mq.SeckillOrderTo;
import com.sq.common.utils.R;
import com.sq.common.vo.MemberRespVo;
import com.sq.gulimall.seckill.feign.CouponFeignService;
import com.sq.gulimall.seckill.feign.ProductFeignService;
import com.sq.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.sq.gulimall.seckill.service.SeckillService;
import com.sq.gulimall.seckill.to.SeckillSkuRedisTo;
import com.sq.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.sq.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //sku的库存信号量  +商品的随机码

    /**
     * 上传最近三天的秒杀活动信息
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描最近三天需要参加的秒杀活动
        R session = couponFeignService.getLatest3DaysSession();
            if(session != null){
                if (session.getCode() == 0) {
                    //上架商品 将返回的数据 封装成指定的Vo
                    List<SeckillSessionsWithSkus> sessionData = session.getData(
                            new TypeReference<List<SeckillSessionsWithSkus>>() {
                            });

                    //缓存到Redis
                    //1. 缓存活动信息
                    saveSessionInfos(sessionData);
                    //2. 缓存活动的关联商品信息
                    saveSessionSkuInfos(sessionData);
                }
            }
    }

    /**
     * blockHandler 函数会在原方法被限流/降级/系统保护的时候调用，而fallback 函数会针对所有类型的异常。
     * @param e
     * @return
     */
    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkusResource...被限流了...");
        return null;
    }

    /**
     * 获取 当前时间 可以参加 秒杀活动的商品信息
     *
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间 属于哪个秒杀场次。
        //1970 - 1970年到当前时间的 时间差
        long time = new Date().getTime();

        //定义一段受保护的资源
        try(Entry entry = SphU.entry("seckillSkus")){
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                //"seckill:sessions:1646964000000_1646971200000"
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);

                //当前时间 符合的秒杀场次
                if (time >= start && time <= end) {
                    //获取这个秒杀场次 需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null); //当前秒杀开始了，就需要随机码，不必隐藏
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break; //已经查到当前秒杀活动的场次，break结束循环
                }
            }
        }catch(BlockException e){
            log.error("资源被限流....{}",e.getMessage());
        }

        return null;
    }

    /**
     * 获取sku商品的秒杀活动信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        //1.找到所有 需要参与秒杀的商品 的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {

            String regx = "\\d*_" + skuId;
            for (String key : keys) {
                //6_4
                if (Pattern.matches(regx, key)) {
                    System.out.println("匹配到sku参与的秒杀活动信息.....");
                    //找到匹配的数据，从Redis中取出来，把json数据转换成对应的To对象
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    //随机码
                    long current = new Date().getTime();
                    if (current >= skuRedisTo.getStartTime() && current <= skuRedisTo.getEndTime()) {
                    } else {
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * 执行秒杀操作
     * TODO 上架秒杀商品的时候，每一个数据都有一个过期时间。
     * TODO 秒杀后续的流程，简化了收货地址等信息。
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();

        // 获取当前登录用户的所有信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
//            return null;
        } else {
            //从Redis中取出的数据
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long now = new Date().getTime();
            long ttl = endTime - now; //redis的占位锁过期时间 秒杀场次结束，占位锁过期
            //1.校验时间的合法性
            if (now >= startTime && now <= endTime) {
                //2.校验随机码和 商品id
                String randomCode = redis.getRandomCode();
                String sessionId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && sessionId.equals(killId)) {
                    //3.验证购买的数量是否合理
                    if (num <= redis.getSeckillLimit()) {
                        //4.验证这个人是否已经购买过  幂等性处理 如果只要秒杀成功，就去占位。 userId_SessionId_skuId
                        //SETNX
                        String redisKey = memberRespVo.getId() + "_" + sessionId;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey,
                                num.toString(),
                                ttl,
                                TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                            // .acquire()是阻塞方法  阻塞等待，性能太低
                            boolean b = semaphore.tryAcquire(num);
                            if (b) { //获取信号量成功，才能秒杀
                                //秒杀成功
                                //快速下单，发送MQ消息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(memberRespVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange",
                                        "order.seckill.order", orderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("耗时.....{}", (s2 - s1));

                                return timeId; //返回秒杀成功的订单号
                            }

                            return null;
                        } else {

                            //占位失败说明已经买过了
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            }
        }
        return null; //秒杀失败，返回空结果
    }

    /**
     * 缓存商品的活动信息
     *
     * @param sessions
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        if(sessions != null){
            sessions.forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                //判断数据是否已经上架了，有key就不做了，没有key才做
                if (!hasKey) {
                    List<String> collect = session.getRelationSkus().stream()
                            //收集活动场次id + 活动的sku的id
                            .map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    //缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    /**
     * 缓存秒杀活动的关联商品信息
     *
     * @param sessions
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {
        if(sessions != null){
            sessions.stream().forEach(session -> {
                //准备hash操作
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    // 生成秒杀商品的随机码
                    String token = UUID.randomUUID().toString().replace("-", "");

                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString())) {
                        //缓存商品
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        //1.sku的基本数据
                        R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfoVo(info);
                        }

                        //2.sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3.设置上当前商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        //4.商品的随机码 秒杀开始的时候暴露，保证秒杀公平性
                        redisTo.setRandomCode(token);

                        String jsonString = JSON.toJSONString(redisTo);
                        ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);

                        //5.使用库存，作为分布式的信号量  使用商品的唯一随机码 获取商品的信号量 限流
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量 作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }

                });
            });
        }
    }
}
